<?php

namespace App\V3\V3_2_7\Controllers;

use App\V3\V3_2_7\Models\SystemConfigModel;
use Illuminate\Http\Request;
use App\V3\V3_2_7\Models\AdminModel;
use OSS\OssClient;
use App\V3\V3_2_7\Models\AdminAddendumModel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\V3\V3_2_7\Services\AdminService;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Carbon;
class SystemConfigController extends BaseController
{
    protected $ossClient;
    protected $adminInfo;
    public function __construct(Request $request){
        parent::__construct($request);
        $this->ossClient=new OssClient(
            config('app.aliyun_oss_key'),
            config('app.aliyun_oss_secret'),
            config('app.aliyun_oss_endpoint')
            );
        $this->adminInfo = AdminModel::select('id')
        ->where([
            'id'=>$this->getMainUserId(),
            'delete_flag'=>0,
            'admin_role'=>1,
            ['parent_id', '=', 0]
        ])->first();
    }
    //
    public function set(Request $request)
    {
        if(in_array($request->val, [0, 1])) {
            SystemConfigModel::where('key_value', 'switch')->update(['value' => $request->val]);
            return $this->success();
        }
        else {
            return $this->fail('', '参数不合法');
        }
    }

    public function get()
    {
        $result = SystemConfigModel::where('key_value', 'switch')->first();
        return $this->success(
            $result['value']
        );
    }

    //设置体验版时长
    public function setExperience(Request $request)
    {
        if(!is_numeric($request->value)) {
            return $this->fail('', '输入的内容仅能为数字');
        }

        if(!is_integer($request->value * 1)) {
            return $this->fail('', '输入的内容仅能为整数');
        }
        if($request->value < 0) {
            return $this->fail('', '输入的内容不能小于0');
        }

        SystemConfigModel::where('key_value', 'experience_day')->update(['value' => $request->value]);
        return  $this->success();
    }

    public function getExperience()
    {
        $result = SystemConfigModel::where('key_value', 'experience_day')->first();
        return $this->success(
            $result['value']
        );
    }

    //是否开启系统维护
    public function isUpkeep()
    {
        $info = SystemConfigModel::where('key_value', 'is_upkeep')->first();

        if($info['value']) {
            $info->value = 0;
            $info->save();
            $tag = 0;
        }
        else {
            $info->value = 1;
            $info->save();
            $tag = 1;
        }

        return $this->success($tag);
    }

    //获取开启系统维护信息
    public function getIsUpkeep()
    {
        $info = SystemConfigModel::select('value')->where('key_value', 'is_upkeep')->first();
        return $this->success((int)$info['value']);
    }
    /**
     * 系统微信群图片上传
     * @param Request $request
     */
    public function wxqImgUpload(Request $request){
        $aInfo = AdminModel::select('admin_role')->where(['id'=>$this->getUserId()])->where('delete_flag',0)->first();
        if($aInfo['admin_role'] != 1) return $this->fail('','您不是超级管理员，不能上传系统微信群图片！');
        $sInfo = SystemConfigModel::where(['key_value'=>'wxq_img'])->first();
        if(!empty($file = $request->file('wxq_img'))){
            $img_path = "";
            $res = self::handlePicFormat($file);//判断文件格式
            if(!empty($res)) return $this->fail('',$res['msg']);
            if($file->isValid()){
                $img_path = $file->store('xt/wxq/img/'.date('Y').'-'.date('m').'-'.date('d'));
                $res = SELF::addOssUploadImg($this->getMainUserId(), $this->ossClient, $file, $img_path);
                if($res['code'] == 1) return $this->fail('',$res['msg']);
                $img_path = $res['data'];
            }else{
             return $this->fail('','系统微信群图片，上传失败！');
            }
            DB::getDefaultConnection();
            try {
            if(empty($sInfo)){
                SystemConfigModel::insertGetId(['key_value'=>'wxq_img','value'=>$img_path,'upload_at'=>time()]);
            }else{
                //删除oss里的文件
                $delOssRes = self::delOssFilePath($sInfo['value'], $this->ossClient, $this->getMainUserId());
                if(!empty($delOssRes)) return $this->fail('',$delOssRes);
                SystemConfigModel::where(['key_value'=>'wxq_img'])->update(['value'=>$img_path,'upload_at'=>time()]);
            }
            DB::commit();
            return $this->success($img_path);
            } catch (\Exception $e) {
                DB::rollback();
                Log::debug('出库：'.var_export($e->getMessage(), true));
               return $this->fail('','系统微信群图片,上传异常');
            }
        }else{
            return $this->fail('','请选择一个，系统微信群图片！');
        }
    }

    /**
     * 查询系统微信群图片
     * @param Request $request
     */
    public function getWachatGroupImgInfo(Request $request){
        try {

            $sInfo = SystemConfigModel::select('value','upload_at')->where(['key_value'=>'wxq_img'])->first();

            return $this->success(['path'=>$sInfo['value'],'upload_at'=>$sInfo['upload_at']]);
            } catch (\Exception $e) {
                return $this->success(['path'=>""]);
            }
    }
    /**
     * 图片上传到oss系统
     * @param unknown $client
     * @param unknown $file
     */
    static public function addOssUploadImg($mainId,$client,$file,$path){

        $res = handleUploadFileType($file);
        if(!empty($res)) return $res;
        $size = $file -> getSize();
        $result = saveFileSize(['main_id'=>$mainId], $size,$path);
        if($result['code'] == 1) return $result;
        try {

            $fullPath = '/uploads/'.$path;
            $ossPath  = ltrim($fullPath,'./');
            $path     = public_path().$fullPath;
            $client -> uploadFile(config('app.aliyun_oss_bucket'), $ossPath, $path);

            @unlink($path);
            $url = config('app.aliyun_oss_bucket_url').$fullPath;
            return ["code"=>0,"msg"=>"success","data"=>$url];

        } catch (\Exception $e) {

            return ["code"=>1,"msg"=>"OSS系统，上传图片失败！","data"=>""];
        }
    }

    /**
     * 处理图片和视频格式
     */
    static public function handlePicFormat($files){

        $pic_format  = 'bmp,jpg,png,tif,gif,pcx,tga,exif,fpx,svg,psd,cdr,pcd,dxf,ufo,eps,ai,raw,wmf,webp,avif,apng';
        $ext = $files->extension();

        $ext = strtolower($ext);

      $pic_video_format_arr = explode(',',$pic_format);

        if (!in_array($ext, $pic_video_format_arr)) {

            return ['code' => 1,'msg' => '图片格式，不正确','data' => ''];
        }

    }

    /**
     * 删除oss里的文件
     * @param unknown $file
     * @param unknown $mainId
     */
    static public function delOssFilePath($file,$client,$mainId){

        if(empty($file)) return $file;

        DB::beginTransaction();
        try {
            $delPath = strstr($file, 'uploads/');
            $imgInfo=$client->getObjectMeta(config('app.aliyun_oss_bucket'), $delPath);
            AdminAddendumModel::where(['main_id'=>$mainId])
            ->decrement('file_total_size', $imgInfo['content-length']);
            $client -> deleteObject(config('app.aliyun_oss_bucket'), $delPath);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();

        }
    }

    /**
     * 用户列表
     * @param Request $request
     */
    public function getUserList(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'pageSize' =>'required|integer',//页面大小
            'currentPage' =>'required|integer',//当前页
        ],[
            'pageSize.required' => '参数`pageSize`缺失',
            'pageSize.integer' => '参数`pageSize`仅能为数字',
            'currentPage.required' => '参数`currentPage`缺失',
            'currentPage.integer' => '参数`currentPage`仅能为数字',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return fail('', $info);
        }
        $list = [];
        if(!empty($this->adminInfo)){
            $list = AdminService::getUserList($data);
            if(!empty($list['data'])){
                foreach ($list['data'] as &$val){
                    if(!empty($val['vip_end_date'])){
                        $val['vip_end_date']= Carbon::createFromTimestamp($val['vip_end_date'])->format('Y-m-d H:i:s');
                    }
                    if(!empty($val['storage_end_date'])){
                        $val['storage_end_date'] = Carbon::createFromTimestamp($val['storage_end_date'])->format('Y-m-d H:i:s');
                    }
                }
                $list['reg_total_num'] = AdminModel::select(
                    DB::raw('count(*) as reg_num')
                    )->where([
                        'delete_flag' => 0,
                        'is_active'=>1,
                        ['parent_id','=',0],
                    ])->first()['reg_num']??0;
                $list['vip_total_num'] = AdminModel::select(
                    DB::raw('count(*) as vip_num')
                    )->from('admin as a')
                    ->leftJoin('admin_addendum as b', 'b.main_id', '=', 'a.id')
                    ->where([
                        'delete_flag' => 0,
                        'is_active'=>1,
                        ['parent_id','=',0],
                        'b.is_vip'=>1
                    ])->first()['vip_num']??0;
            }
        }

        return success($list);
    }

    /**
     * 用户管理列表
     * @param Request $request
     */
    public function getUserManageList(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'pageSize' =>'required|integer',//页面大小
            'currentPage' =>'required|integer',//当前页
        ],[
            'pageSize.required' => '参数`pageSize`缺失',
            'pageSize.integer' => '参数`pageSize`仅能为数字',
            'currentPage.required' => '参数`currentPage`缺失',
            'currentPage.integer' => '参数`currentPage`仅能为数字',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return fail('', $info);
        }
        $list = [];
        if(!empty($this->adminInfo)){
            $list = AdminService::getUserManageList($data);
        }

        return success($list);
    }

    /**
     * 设置标记用户列表
     * @param Request $request
     */
    public function getLabelUserList(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'pageSize' =>'required|integer',//页面大小
            'currentPage' =>'required|integer',//当前页
        ],[
            'pageSize.required' => '参数`pageSize`缺失',
            'pageSize.integer' => '参数`pageSize`仅能为数字',
            'currentPage.required' => '参数`currentPage`缺失',
            'currentPage.integer' => '参数`currentPage`仅能为数字',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return fail('', $info);
        }
        $list = [];
        if(!empty($this->adminInfo)){
            $data['label'] = 1;
            $list = AdminService::getUserManageList($data);
        }

        return success($list);
    }

    /**
     *重置体验VIP
     * Author: zlf
     * Created at 2024/1/3 14:20
     * @param Request $request
     * @return void
     */
    public function resetExperVip(Request $request)
    {
        if($this->getUserId() != 1){
            return fail('','您无权请求！');
        }
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'phone' =>'required|regex:/^1[3456789]\d{9}$/',//账号
        ],[
            'phone.required' => '账号参数`phone`缺失',
            'phone.regex' => '账号格式不正确，请重新输入！',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return fail('', $info);
        }
        try{
            AdminAddendumModel::where(
                'main_id',
            AdminModel::where(['username'=>$data['phone']]
            )->value('id'))->update([
            'vip_end_date' => 0,
            'is_in_experience' => 0,
            'is_end_experience' => 0,
            ]);
            return success();
        }catch (\Exception $e){
            return fail('',$e->getMessage());
        }
    }
}
